﻿
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace BusinessManage.Common
{
    public class Base64Code
    {
        /// <summary>
        /// 将Base64字符串转化为文件并保存在磁盘上
        /// </summary>
        /// <param name="strbase64"></param>
        /// <param name="DirectoryPath">保存文件夹路径</param>
        /// <param name="extname">文件扩展名</param>
        /// <returns></returns>
        public static string SaveFile(string strbase64, string DirectoryPath, string extname)
        {
            string filename = System.Guid.NewGuid().ToString() + extname;

            byte[] byteArray = Convert.FromBase64String(strbase64);
            string path = DirectoryPath + filename;
            //使用文件流读取byte数组中的数据
            using (Stream s = new FileStream(path, FileMode.Append))
            {
                s.Write(byteArray, 0, byteArray.Length);
                s.Close();
            }
            return filename;
        }//字符串转换base64编码
        public static string StringToBase64(string str)
        {
            if (str != "" && str != null)
            {
                byte[] b = Encoding.Default.GetBytes(str);
                string returnstr = Convert.ToBase64String(b);
                return returnstr;
            }
            else
            {
                return "";
            }
        }
        public static string FileToBase64(string path)
        {
            string base64Str = "";
            using (FileStream filestream = new FileStream(path, FileMode.Open))
            {

                byte[] bt = new byte[filestream.Length];

                //调用read读取方法 

                filestream.Read(bt, 0, bt.Length);
                base64Str = Convert.ToBase64String(bt);
                filestream.Close();
            }
            return base64Str;
        }
    }
}